package com.apanal.qlife.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.util.FileOperateUtil;

/**
 * URL过滤器
 * 
 * @author shuliangxing
 * 
 * @date 2014-12-9下午3:49:09
 */
public class UrlFilter implements Filter {

	public void init(FilterConfig arg0) throws ServletException {

	}

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain filterChain) throws IOException, ServletException {
		if (!(req instanceof HttpServletRequest)
				|| !(resp instanceof HttpServletResponse)) {
			throw new ServletException(
					"OncePerRequestFilter just supports HTTP requests");
		}
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		// request.setCharacterEncoding("utf-8");
		// response.setCharacterEncoding("utf-8");
		// response.setContentType("text/html;charset=UTF-8");

		// 设置超时时间,单位秒
		// request.getSession().setMaxInactiveInterval(30*60);

		String contextPath = request.getContextPath();
		// 设置当前web环境上下文，用于方便如JSP页面使用
		request.setAttribute(Constants.CONTEXT_PATH, contextPath);
		// 文件服务器访问url
		String fileUrl = Constants.FILE_UPLOAD_URL;
		if (StringUtils.isEmpty(fileUrl)) {
			fileUrl = FileOperateUtil.DEFAULT_UPLOADDIR;
		}
		if (!fileUrl.startsWith("http")) {
			if (!fileUrl.startsWith("/")) {
				fileUrl = "/" + fileUrl;
			}
			fileUrl = contextPath + fileUrl;
		}
		if (!fileUrl.endsWith("/")) {
			fileUrl += "/";
		}
		// 设置文件服务器访问url，用于方便如JSP页面使用
		request.setAttribute(Constants.FILE_UPLOAD_URL_KEY, fileUrl);

		// iframe引起第三方网站cookie丢失
		// response.setHeader("P3P", "CP=CAO PSA OUR");
		response.setHeader("P3P",
				"CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");

		filterChain.doFilter(request, response);
	}

}
